package com.buydeem.share.hystrixdemo;

import com.buydeem.share.hystrixdemo.model.User;
import com.buydeem.share.hystrixdemo.service.UserService;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import lombok.extern.slf4j.Slf4j;

/**
 * Hystrix缓存
 * @author zengchao
 * @version 1.0.0
 * @ClassName App2.java
 * @Description TODO
 * @createTime 2021年04月05日 21:20:00
 */
@Slf4j
public class App2 {
    public static void main(String[] args) {
        //需要在同一个HystrixRequestContext中
        HystrixRequestContext context1 = HystrixRequestContext.initializeContext();
        User context1Mac;
        try {
            User mac1 = new QueryFromCache("mac").execute();
            User mac2 = new QueryFromCache("mac").execute();
            log.info("mac1 == mac2 ? {}",mac1 == mac2);
            context1Mac = mac1;
        }finally {
            context1.shutdown();
        }

        HystrixRequestContext context2 = HystrixRequestContext.initializeContext();
        try {
            User mac = new QueryFromCache("mac").execute();
            //不是同一个HystrixRequestContext中的对象不一样
            log.info("mac == context1Mac ? {}",mac == context1Mac);
        }finally {
            context2.shutdown();
        }
    }
}

@Slf4j
class QueryFromCache extends HystrixCommand<User> {
    private final String name;
    private final UserService userService = new UserService();

    public QueryFromCache(String name) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("group_key"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("command_key")));
        this.name = name;
    }

    @Override
    protected User run() throws Exception {
        return userService.queryUser(name);
    }

    //需要实现getCacheKey方法
    @Override
    protected String getCacheKey() {
        return name;
    }
}
